import { Button, message, Popconfirm, Space, Table } from "antd"
import moment from "moment"
import { useRef } from "react";
import { useRequest } from "umi"
import EditForm from "./editForm";

const UserManger = () => {
  const modelComRef: any = useRef(null);
  const { data, loading, run } = useRequest({
    url: '/api/user/findAll'
  })
  const { run: delApi, loading: delLoading } = useRequest((req) => ({
    url: '/api/user/delUser',
    method: 'post',
    data: req
  }), { manual: true })

  const handleDel = async (username: string) => {
    await delApi({ username })
    message.success('操作成功')
    run()
  }
  const columns = [
    { title: '用户名', dataIndex: 'username' },
    { title: '角色', dataIndex: 'roleName' },
    { title: '创建时间', dataIndex: 'createTime', render: (text: string) => (
      moment(text).format('yyyy-MM-DD HH:mm:ss')
    ) },
    { title: '操作', render: (text: any, record: any) => (
      <Space>
        <Button onClick={ () => modelComRef.current.open(2, record) } size="small" type="primary">编辑</Button>
        <Popconfirm title="确认删除？" onConfirm={() => handleDel(record.username) } okButtonProps={{ loading: delLoading }}>
          <Button size="small" danger>删除</Button>
        </Popconfirm>
      </Space>
    ) },
  ]

  return <>
    <Table rowKey='id' dataSource={data} loading={loading} columns={columns} />
    <EditForm submit={() => run()} cRef={modelComRef} />
  </>
}

export default UserManger